const SQL_NAME = "zengcaimei-h5";
const DB_NAME = "h5";

class indexDb {
	name: string; // 主键
	request: any;
	db: any;
	constructor(name: string) {
		this.name = name;
	}

	init() {
		return new Promise((resolve, reject) => {
			this.request = window.indexedDB.open(SQL_NAME);
			this.request.onerror = (event: any) => {
				reject(event);
				// Toast("缓存获取失败");
			};
			this.request.onsuccess = (event: any) => {
				resolve(event.target.result);
				this.db = event.target.result;
			};
			this.request.onupgradeneeded = (event: any) => {
				this.db = event.target.result;
				let objectStore;
				if (!this.db.objectStoreNames.contains(DB_NAME)) {
					objectStore = this.db.createObjectStore(DB_NAME, {
						keyPath: "name",
						unique: true, // 名称作为主键不允许重复
					});
					objectStore.createIndex("content", "content", {
						unique: false
					});
				}
			};
		});
	}

	async get(name: string) {
		return new Promise((resolve, reject) => {
			const transaction = this.db.transaction([DB_NAME], "readonly");
			const objectStore = transaction.objectStore(DB_NAME);
			const req = objectStore.get(name);

			req.onsuccess = function() {
				resolve(req.result);
			};
			req.onerror = reject;
		});
	}

	async add(content: string) {
		return new Promise((resolve, reject) => {
			const select = this.db
				.transaction([DB_NAME], "readwrite")
				.objectStore(DB_NAME)
				.add({
					name: this.name,
					content
				});

			select.onsuccess = (event: any) => {
				resolve(event.target.result);
			};
			select.onerror = reject;
		});
	}

	async update(name: string, content: string) {
		return new Promise((resolve, reject) => {
			const select = this.db
				.transaction([DB_NAME], "readwrite")
				.objectStore(DB_NAME)
				.put({
					name,
					content
				});

			select.onsuccess = (event: any) => {
				resolve(event.target.result);
			};
			select.onerror = reject;
		});
	}
}

export default indexDb;